/*
 * This class will handle request in getting Meal Comment information from Server
 * All the information would be wrapped in MealComment Class object
 */

package com.controller;

//need to fetch multiple comment

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.configuration.Configuration;
import com.configuration.Owner;
import com.object.MealComment;
import com.user.JSONParser;

public class MealCommentFetch {
	//URL for fetching data
	private static String fetchMealCommentByIdURL 			= "http://128.199.214.245/android/MealCommentFetch/fetch_meal_comment_by_id.php";
	private static String fetchAllMealCommentCommentURL 	= "http://128.199.214.245/android/MealCommentFetch/fetch_all_meal_comment.php";
	private static String fetchMealCommentCommentByMealIdURL= "http://128.199.214.245/android/MealCommentFetch/fetch_meal_comment_by_meal_id.php";
	private static String isLikedByUserURL					= "http://128.199.214.245/android/MealCommentFetch/is_liked_by_user.php";
	private static String fetchMealCommentByUserIdURL		= "http://128.199.214.245/android/MealCommentFetch/fetch_meal_comment_by_user_id.php";
	//Mainly for the following page
	private static String fetchMealCommentByFollowerIdURL	= "http://128.199.214.245/android/MealCommentFetch/fetch_meal_comment_by_follower_id.php";
	

	//Keys for the Json field
	/*
	 * KEY_STATUS shows the status of the request
	 * 0 : Fail to get restaurant
	 * 1 : Successfully in getting restaurant
	 */
	private String KEY_ID				= "ID";
	private String KEY_USER				= "USER";
	private String KEY_MEAL				= "MEAL";
	private String KEY_COMMENT			= "COMMENT";
	private String KEY_CREATE_DATE		= "CREATE_DATE";
	private String KEY_RESULT			= "RESULT";
	private String KEY_STATUS 			= "STATUS";
	private String KEY_NUMBER 			= "NUMBER";		//Returned by server telling how many restaurants 
	    
	private String FAIL 	= "0";
	private String SUCCESS 	= "1";
	    
	//For making httpRequest
	private JSONParser jsonParser;
	private JSONObject result;
	List<NameValuePair> params;
	
	//Constructor
	public MealCommentFetch(){
	    jsonParser = new JSONParser();
	}
	
	/*
	 * fetchMealCommentById function will return an Restaurant object based on Restaurant id entered
	 * - non-null	: Data of the Restaurant with id = id
	 * - null		: No such Restaurant
	 */
	public MealComment fetchMealCommentById(int id){
		//Get Json object
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("id",Integer.toString(id)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchMealCommentByIdURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch","fetchMealCommentById - Restaurant Comment found");
					} 
					
					// Store information to object
					//int id = Integer.parseInt(result.getString(KEY_ID));
					int user 				= Integer.parseInt(result.getString(KEY_USER));
					//int UserID
					int meal	 			= Integer.parseInt(result.getString(KEY_MEAL));
					String comment			= result.getString(KEY_COMMENT);
					String createDate		= result.getString(KEY_CREATE_DATE);
					
					MealComment mealComment = new MealComment(id,user,meal,comment,createDate);					
					
					return mealComment;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch","fetchMealCommentById - Unable to find meal comment");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealCommentFetch","fetchMealCommentById - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealCommentFetch","fetchMealCommentById - Exception");
			}
		}

		return null;
	}
	
	/*
	 * fetch meal comment based on meal id
	 */
	public List<MealComment> fetchMealCommentByMealId(int meal){
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        //No parameter
        params.add(new BasicNameValuePair("meal",Integer.toString(meal)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchMealCommentCommentByMealIdURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch","fetchMealCommentByMealId - Meal found");
					}
					
					int numberOfMealComment = Integer.parseInt(result.getString(KEY_NUMBER));
					
					List <MealComment> mealCommentList = new ArrayList<MealComment>();
					
					JSONArray idArray 				= result.getJSONArray(KEY_ID);
					JSONArray userArray 			= result.getJSONArray(KEY_USER);
					//JSONArray mealArray			= result.getJSONArray(KEY_MEAL);
					JSONArray commentArray 			= result.getJSONArray(KEY_COMMENT);
					JSONArray createDateArray 		= result.getJSONArray(KEY_CREATE_DATE);

					for(int i=0;i<numberOfMealComment;i++){
						// Store information to object
						
						int	id					= Integer.parseInt(idArray.getString(i));
						int user				= Integer.parseInt(userArray.getString(i));
						//int meal				= Integer.parseInt(mealArray.getString(i));
						String comment			= commentArray.getString(i);
						String createDate		= createDateArray.getString(i);

						
						MealComment mealComment = new MealComment(id,user,meal,comment,createDate);
						mealCommentList.add(mealComment);
						
					}
					
					return mealCommentList;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch","fetchMealCommentByMealId - Unable to find restaurant comment");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealCommentFetch","fetchMealCommentByMealId - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealCommentFetch","fetchMealCommentByMealId - Exception");
			}
		}
		return null;
	}
	
	/*
	 * fetch all meal comment
	 */
	public List<MealComment> fetchAllMealComment(){
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        //No parameter
        //params.add(new BasicNameValuePair("id",Integer.toString(id)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchAllMealCommentCommentURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch","fetchAllMealComment - Restaurant found");
					}
					
					int numberOfMealComment = Integer.parseInt(result.getString(KEY_NUMBER));
					
					List <MealComment> mealCommentList = new ArrayList<MealComment>();
					
					JSONArray idArray 				= result.getJSONArray(KEY_ID);
					JSONArray userArray 			= result.getJSONArray(KEY_USER);
					JSONArray mealArray				= result.getJSONArray(KEY_MEAL);
					JSONArray commentArray 			= result.getJSONArray(KEY_COMMENT);
					JSONArray createDateArray 		= result.getJSONArray(KEY_CREATE_DATE);

					for(int i=0;i<numberOfMealComment;i++){
						// Store information to object
						
						int	id					= Integer.parseInt(idArray.getString(i));
						int user				= Integer.parseInt(userArray.getString(i));
						int meal				= Integer.parseInt(mealArray.getString(i));
						String comment			= commentArray.getString(i);
						String createDate		= createDateArray.getString(i);

						
						MealComment mealComment = new MealComment(id,user,meal,comment,createDate);
						mealCommentList.add(mealComment);
						
					}
					
					return mealCommentList;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch","fetchAllMealComment - Unable to find restaurant comment");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealCommentFetch","fetchAllMealComment - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealCommentFetch","fetchAllMealComment - Exception");
			}
		}
		return null;
	}
	
	public boolean isLikedByUser(int mealId,int userId){
		//Get Json object
		// Building Parameters
		params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("meal_id",Integer.toString(mealId)));
		params.add(new BasicNameValuePair("user_id",Integer.toString(userId)));
			        
		//Start a new thread and use POST method to send telephone and passcode to authURL
		//Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(isLikedByUserURL,"POST",params);
			}
		});  
		attemptThread.start();
						
		while(attemptThread.isAlive()){
			//Wait for server response
		}
						
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch"," isLikedByUser - Meal found");
					}
									
					// Return the name of the restaurant
					if(Integer.parseInt(result.getString(KEY_RESULT)) == 1){
						return true;
					}else{
						return false;
					}
									
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch"," isLikedByUser - Unable to find restaurant");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealCommentFetch"," isLikedByUser - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealCommentFetch"," isLikedByUser - Exception");
			}
		}
		return false;
	}
	
	
	public List<MealComment> fetchMealCommentByUserId(int userId){
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        //No parameter
        params.add(new BasicNameValuePair("user",Integer.toString(userId)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchMealCommentByUserIdURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch","fetchMealCommentByMealId - Meal found");
					}
					
					int numberOfMealComment = Integer.parseInt(result.getString(KEY_NUMBER));
					
					List <MealComment> mealCommentList = new ArrayList<MealComment>();
					JSONArray idArray 				= result.getJSONArray(KEY_ID);
					JSONArray userArray 			= result.getJSONArray(KEY_USER);
					JSONArray mealArray				= result.getJSONArray(KEY_MEAL);
					JSONArray commentArray 			= result.getJSONArray(KEY_COMMENT);
					JSONArray createDateArray 		= result.getJSONArray(KEY_CREATE_DATE);
					
					for(int i=0;i<numberOfMealComment;i++){
						// Store information to object
						
						int	id					= Integer.parseInt(idArray.getString(i));
						int user				= Integer.parseInt(userArray.getString(i));
						int meal				= Integer.parseInt(mealArray.getString(i));
						String comment			= commentArray.getString(i);
						String createDate		= createDateArray.getString(i);

						MealComment mealComment = new MealComment(id,user,meal,comment,createDate);
						mealCommentList.add(mealComment);
						
					}
					
					return mealCommentList;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch","fetchMealCommentByMealId - Unable to find restaurant comment");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealCommentFetch","fetchMealCommentByMealId - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealCommentFetch","fetchMealCommentByMealId - Exception");
			}
		}
		return null;
	}
	
	//Get the list for priniting the following page
	public List<MealComment> fetchMealCommentByFollowerId(int userId){
		// Building Parameters
        params = new ArrayList<NameValuePair>();
        //No parameter
        params.add(new BasicNameValuePair("user",Integer.toString(userId)));
        
        //Start a new thread and use POST method to send telephone and passcode to authURL
        //Start a new thread to attempt Login (requirement when connecting online)
		Thread attemptThread = new Thread(new Runnable(){  
			public void run(){  
				result = jsonParser.makeHttpRequest(fetchMealCommentByFollowerIdURL,"POST",params);
			}
		});  
		attemptThread.start();
		
		while(attemptThread.isAlive()){
			//Wait for server response
		}
		
		//Parse the json object
		try {
			if(result.getString(KEY_STATUS) != null){
				//Able to get response from server
				if(result.getString(KEY_STATUS).equalsIgnoreCase(SUCCESS)){
					//Successful in finding the Restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch","fetchMealCommentByMealId - Meal found");
					}
					
					int numberOfMealComment = Integer.parseInt(result.getString(KEY_NUMBER));
					
					List <MealComment> mealCommentList = new ArrayList<MealComment>();
					JSONArray idArray 				= result.getJSONArray(KEY_ID);
					JSONArray userArray 			= result.getJSONArray(KEY_USER);
					JSONArray mealArray				= result.getJSONArray(KEY_MEAL);
					JSONArray commentArray 			= result.getJSONArray(KEY_COMMENT);
					JSONArray createDateArray 		= result.getJSONArray(KEY_CREATE_DATE);
					
					for(int i=0;i<numberOfMealComment;i++){
						// Store information to object
						
						int	id					= Integer.parseInt(idArray.getString(i));
						int user				= Integer.parseInt(userArray.getString(i));
						int meal				= Integer.parseInt(mealArray.getString(i));
						String comment			= commentArray.getString(i);
						String createDate		= createDateArray.getString(i);

						MealComment mealComment = new MealComment(id,user,meal,comment,createDate);
						mealCommentList.add(mealComment);
						
					}
					
					return mealCommentList;
					
				}else{
					//Fail to find such restaurant
					if(Configuration.showLog){
						Log.d("MealCommentFetch","fetchMealCommentByMealId - Unable to find restaurant comment");
					}
				}
			}else{
				//unable to get response from server
				if(Configuration.showLog){
					Log.d("MealCommentFetch","fetchMealCommentByMealId - Unable to get response from server");
				}
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			if(Configuration.showLog){
				Log.d("MealCommentFetch","fetchMealCommentByMealId - Exception");
			}
		}
		return null;
	}
}
